package it.truestoryfactory.tsq.game;

import java.util.ArrayList;
import java.util.List;

import it.truestoryfactory.tsq.R;
import it.truestoryfactory.tsq.game.db.TSQuestion;
import it.truestoryfactory.tsq.game.util.ScoreFragment;
import android.app.ListFragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class QuestionFragment extends ListFragment {
	
	private View myContentView;
	private long time=0;
	private List<String> answers = new ArrayList<String>();
	private int timeout;
	
	private TSQuestion quest;
	private ScoreFragment scoreFrag;
	private CountDownTimer countDown;
	 
	 @Override
	public void onActivityCreated(Bundle savedInstanceState) {
		Log.d(this.getClass().getName(), "onActivity created");
		super.onActivityCreated(savedInstanceState);
        this.setListAdapter(new AnswerListAdapter(getActivity(), R.layout.answer, answers));
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		Log.d(this.getClass().getName(), "onCreateView");
		startTimer();
		countDown = new CountDownTimer(timeout+1000, 1000) {
			
			private boolean firstTick = true;
			private int timeLeft;

			@Override
			public void onTick(long millisUntilFinished) {
				Log.d(this.getClass().getName(), "tick with " + millisUntilFinished + " left...");
				if (firstTick ){
					load();
					timeLeft = timeout / 1000;
					firstTick = false;
				}
				
				if (timeLeft >= 0)
					scoreFrag.setTimeOutView(timeLeft--);
				
			}
			
			@Override
			public void onFinish() {
				
				if (myContentView.findViewById(android.R.id.list).isEnabled()) {
					myContentView.findViewById(android.R.id.list).setEnabled(false);
					((GameActivity)getActivity()).myService.sendAnswerMessage(timeout+1001, null);
				}
				
				scoreFrag.setTimeOutView("TIME OUT!");
				
			}
		};
		countDown.start();
		myContentView = inflater.inflate(R.layout.question_fragment, null);		
		return myContentView;
	}
	
	@Override
	public void onDestroyView() {
		countDown.cancel();
		super.onDestroyView();
	}
	
	private void startTimer() {
		time=SystemClock.elapsedRealtime();
	}

	public void setTimeout(int sec4qst) {
		timeout=sec4qst*1000;
	}
	
	public void setQuestion(TSQuestion quest) {
		
		this.quest = quest;
		
		Log.d(this.getClass().getName(), "Answers list setting");
		this.answers.clear();
		for (int i = 0; i < quest.getAnswers().length; i++) {
			this.answers.add(i, quest.getAnswers()[i]);
		}
		
		//l'ho messo in update
		//((AnswerListAdapter) getListAdapter()).notifyDataSetChanged();
		//non si sa a cosa serve...
		/*if (this.answers.size() == 0) {
			return;
		}*/

	}
	
	//class adapter
	private class AnswerListAdapter extends ArrayAdapter<String> {
		
		private List<String> items;
		
		public AnswerListAdapter(Context context, int textViewResourceId, List<String> objects) {
            super(context, textViewResourceId, objects);
            Log.d(this.getClass().getName(), "Answers list adapter initiated");
            items=objects;
		}
		
		@Override
        public View getView(int position, View convertView, ViewGroup parent) {
    		Log.d(this.getClass().getName(), "Answers list adapter get view for pos " + position);
        	View view = convertView;
        	
        	if (view == null){
        		LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = vi.inflate(R.layout.answer, parent, false);
        	}
        	
        	String answer = items.get(position);
        	
        	if (answer != null) {
                TextView answerText = (TextView) view.findViewById(R.id.answer_text);
                
                if (answerText != null) {
                    answerText.setText(answer);
                }
            }
        	
        	return view;
        }

	}
	
	//non dovrebbe servire
	/*public void clearAnswers() {
		Log.d(this.getClass().getName(), "Clearing answers");
		answers.clear();
		((AnswerListAdapter) getListAdapter()).notifyDataSetChanged();
	}*/
	
	private void load(){
		//carica la domanda e notifica che sono presenti le risposte
		Log.d(this.getClass().getName(), "carico la domanda " + quest.getQuestion());
		TextView questionText = (TextView) (myContentView.findViewById(R.id.question));
		if (questionText != null){
			Log.d(this.getClass().getName(), "carico veramente la domanda " + quest.getQuestion());
			questionText.setText(quest.getQuestion());
		}
		((AnswerListAdapter) getListAdapter()).notifyDataSetChanged();
		
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		Log.d(getClass().getName(),"Clicked for element " + Integer.valueOf(position));
		l.setEnabled(false);
		stopTimer();
		countDown.cancel();
		scoreFrag.setTimeOutView(time+" ms");
		
		if (position == quest.getCorrectAnswer()) {
			((GameActivity)getActivity()).myService.sendAnswerMessage(time,v);
			v.setBackgroundColor(Color.YELLOW);
		}else {
			((GameActivity)getActivity()).myService.sendAnswerMessage(timeout+1001, null);
			v.setBackgroundColor(Color.RED);
		}
	}

	private void stopTimer() {
		time = SystemClock.elapsedRealtime() - time;
	}

	public void setScoreFragment(ScoreFragment scoreFrag) {
		this.scoreFrag = scoreFrag;
	}

}
